<template>
  <div>
    <el-switch
      v-model="draggable"
      active-text="开启拖拽"
      inactive-text="关闭拖拽"
    >
    </el-switch>
    <el-button @click="batchSave" v-if="draggable">批量保存</el-button>
    <el-button type="danger" @click="batchDelete">批量删除</el-button>
    <el-tree
      :data="menus"
      :props="defaultProps"
      :expand-on-click-node="false"
      show-checkbox
      node-key="catId"
      :default-expanded-keys="expandedKey"
      :draggable="draggable"
      :allow-drop="allowDrop"
      @node-drop="handleDrop"
      ref="menuTree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            Append
          </el-button>

          <el-button type="text" size="mini" @click="() => edit(data)">
            Edit
          </el-button>

          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="category3">
        <el-form-item label="分类名称">
          <el-input v-model="category3.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category3.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input
            v-model="category3.productUnit"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      menus: [],
      draggable: false,
      updateNodes: [],
      maxlevel: 0,
      title: "",
      dialogType: "", //edit,add
      expandedKey: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      dialogVisible: false,
      pCid: [],
      category3: {
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        productUnit: "",
        icon: "",
        catId: null,
      },
    };
  },
  methods: {
    getMenus() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        //console.log("找到了找到了", data.data);
        this.menus = data.data;
      });
    },
    batchDelete(){
      let catIds = [];
      let checkedNodes = this.$refs.menuTree.getCheckedNodes();
      console.log("被选中的元素",checkedNodes)
      for(let i = 0;i<checkedNodes.length;i++){
        catIds.push(checkedNodes[i].catId);
      }

      this.$confirm(`是否批量删除【${catIds}】当前菜单？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(catIds, false),
          }).then(({ data }) => {
            console.log("删除成功");
            this.$message({
              message: "菜单批量删除成功",
              type: "success",
            });
            this.getMenus();
          });
        })
        .catch(() => {});
    },
    batchSave() {
      this.$http({
        url: this.$http.adornUrl("/product/category/update/sort"),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false),
      }).then(({ data }) => {
        this.$message({
          message: "菜单顺序修改成功",
          type: "success",
        });
        this.getMenus();
        this.expandedKey = this.pCid;
        this.updateNodes = [];
        this.maxlevel = 0;
        // this.pCid = 0;
      });
    },
    //处理拖拽成功的监听事件
    //拖拽所改变的目录信息都有：父节点id，目录层级以及排列顺序
    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log(
        "handleDrop的四个参数 ",
        draggingNode,
        dropNode,
        dropType,
        ev
      );
      //所有需要的信息都可以从dropNode中获得
      //1.首先要获取当前节点的最新父节点id
      let pCid = 0;
      let siblings = null;
      if (dropType == "before" || dropType == "after") {
        pCid =
          dropNode.parent.data.catId == undefined
            ? 0
            : dropNode.parent.data.catId;
        siblings = dropNode.parent.childNodes;
      } else {
        pCid = dropNode.data.catId;
        siblings = dropNode.childNodes;
      }
      this.pCid.push(pCid);

      //2.得到当前拖拽节点的最新排序
      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId == draggingNode.data.catId) {
          //遍历的是当前正在拖拽的节点
          let catLevel = draggingNode.level;
          //修改层级
          if (siblings[i].level != draggingNode.level) {
            catLevel = siblings[i].level;
            //修改子节点层级
            this.updateChildNodeLevel(siblings[i]);
          }

          this.updateNodes.push({
            catId: siblings[i].data.catId,
            sort: i,
            parentCid: pCid,
            catLevel: catLevel,
          });
        } else {
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
        }
      }
      //3.得到当前拖拽节点的最新层级
      console.log(this.updateNodes);
    },
    //递归修改子节点的层级
    updateChildNodeLevel(node) {
      if (node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          var cNode = node.childNodes[i].data;
          this.updateNodes.push({
            catId: cNode.catId,
            catLevel: node.childNodes[i].level,
          });
          this.updateChildNodeLevel(node.childNodes[i]);
        }
      }
    },
    //老师版本
    allowDrop(draggingNode, dropNode, type) {
      console.log("正在拖拽", draggingNode, dropNode, type);
      this.countNodeLevel(draggingNode);
      //当前正在拖动的节点深度+父节点所在的深度不大于3即可
      let deep = Math.abs(this.maxlevel - draggingNode.level) + 1;
      console.log("深度", deep);

      if (type == "inner") {
        return deep + dropNode.level <= 3;
      } else {
        //只有“inner”类的拖拽才会出现层级大于四的情况，其他情况默认为true就好了
        return deep + dropNode.parent.level <= 3;
      }
    },
    countNodeLevel(node) {
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          if (node.childNodes[i].level > this.maxlevel) {
            this.maxlevel = node.childNodes[i].level;
          }
          this.countNodeLevel(node.childNodes[i]);
        }
      }
    },
    //我觉得不用那么麻烦
    allowDrop2(draggingNode, dropNode, type) {
      console.log("正在拖拽", draggingNode, dropNode, type);
      //因为是三级分类所以最大层数就是3层，要使层数不超过四就是判断当前拖拽的节点draggingNode的层数+要拖到的节点dropNode的级数（该节点是在第几层）不大于3即可
      let deep = 4 - draggingNode.data.catLevel * 1;
      console.log("deep的值", deep);
      if (type == "inner") {
        return deep + dropNode.data.catLevel <= 3;
      } else {
        //只有“inner”类的拖拽才会出现层级大于四的情况，其他情况默认为true就好了
        return true;
      }
    },
    edit(data) {
      this.dialogType = "edit";
      this.title = "修改分类";
      console.log("正在编辑信息", data);
      this.dialogVisible = true;

      //发送请求获取当前节点的最新数据
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get",
      }).then(({ data }) => {
        //请求成功
        this.category3.name = data.data.name;
        this.category3.catId = data.data.catId;
        this.category3.icon = data.data.icon;
        this.category3.productUnit = data.data.productUnit;
        this.category3.parentCid = data.data.parentCid;
      });
    },
    submit() {
      if (this.dialogType == "add") {
        this.addCategory();
      } else if (this.dialogType == "edit") {
        this.editCategory();
      }
    },
    //修改分类
    editCategory() {
      var { catId, name, icon, productUnit } = this.category3;
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData({ catId, name, icon, productUnit }, false),
      }).then(({ data }) => {
        this.$message({
          message: "修改成功",
          type: "success",
        });
        //关闭对话框
        this.dialogVisible = false;
        this.expandedKey = [this.category3.parentCid];
        this.getMenus();
      });
    },
    //添加三级分类
    addCategory() {
      console.log("获取到菜单信息", this.category3);
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category3, false),
      }).then(({ data }) => {
        this.$message({
          message: "保存成功",
          type: "success",
        });
        //关闭对话框
        this.dialogVisible = false;
        //设置需要默认展开的菜单
        this.expandedKey = [this.category3.parentCid];
        //更新菜单
        this.getMenus();
      });
    },
    append(data) {
      this.dialogType = "add";
      this.title = "添加分类";
      this.dialogVisible = true;
      this.category3.parentCid = data.catId;
      this.category3.catLevel = data.catLevel * 1 + 1;
      this.category3.catId = null;
      this.category3.icon = "";
      this.category3.productUnit = "";
      this.category3.name = "";
    },

    remove(node, data) {
      var ids = [data.catId];

      this.$confirm(`是否删除【${data.name}】当前菜单？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            console.log("删除成功");
            this.$message({
              message: "菜单删除成功",
              type: "success",
            });
            this.expandedKey = [node.parent.data.catId];
            this.getMenus();
          });
        })
        .catch(() => {});
    },
  },
  created() {
    this.getMenus();
  },
};
</script>

<style>
</style>